package com.atguigu.edu.realtime.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PhoenixUtil {
    // 从phoenix表中查询数据的方法
    public static <T> List<T> queryList(Connection conn, String sql, Class<T> clz) {
        // 用于存放查询的结果集
        List<T> resList = new ArrayList<>();

        // 创建数据库操作对象
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            // 执行sql语句
            rs = ps.executeQuery();
            // 获取表结构字段信息
            ResultSetMetaData metaData = rs.getMetaData();
            // 将一条条的结果封装为对象，放入resList集合中
            while (rs.next()) {
                T obj = clz.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i ++) {
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = rs.getObject(i);
                    BeanUtils.setProperty(obj, columnName, columnValue);
                }
                resList.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

        return resList;
    }

    public static void main(String[] args) throws SQLException {
        // 测试是否能够从phoenix表中读取数据
        DruidDataSource druidDataSource = DruidDSUtil.getDruidDataSource();
        DruidPooledConnection conn = druidDataSource.getConnection();

        List<JSONObject> jsonObjects = queryList(conn, "select * from DIM_BASE_CATEGORY_INFO", JSONObject.class);

        for (JSONObject jsonObj : jsonObjects)
            System.out.println(jsonObj.toString());
    }
}
